/*
Copyright (c) 2025 HeZongLun
NahidaProject is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan
PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/

#include "RegisterTable.h"

const char* sub_key = "Software\\ExampleCache";

bool NahidaProject::RegisterTable::SetValue(const std::string& key, const std::string& value) {
	HKEY hkey = nullptr;
	LSTATUS res = ::RegOpenKeyExA(HKEY_CURRENT_USER, sub_key, 0, KEY_WRITE, &hkey);
	if (res != ERROR_SUCCESS) {
		res = ::RegCreateKeyA(HKEY_CURRENT_USER, sub_key, &hkey);
	}
	if (res != ERROR_SUCCESS) {
		return false;
	}
	std::shared_ptr<void> close_key(nullptr, [&](void*) {
		if (hkey != nullptr) {
			::RegCloseKey(hkey);
			hkey = nullptr;
		}
		});
	res = ::RegSetValueExA(hkey, key.c_str(), 0, REG_SZ, (BYTE*)value.c_str(), value.length());
	if (res != ERROR_SUCCESS) {
		return false;
	}
	return true;
}

std::string NahidaProject::RegisterTable::GetValue(const std::string& key) {
	HKEY hkey = nullptr;
	LSTATUS res = ::RegOpenKeyExA(HKEY_CURRENT_USER, sub_key, 0, KEY_READ, &hkey);

	if (res != ERROR_SUCCESS) {
		return "";
	}

	std::shared_ptr<void> close_key(nullptr, [&](void*) {
		if (hkey != nullptr) {
			::RegCloseKey(hkey);
			hkey = nullptr;
		}
		});

	DWORD type = REG_SZ;
	DWORD size = 0;
	res = ::RegQueryValueExA(hkey, key.c_str(), 0, &type, nullptr, &size);

	if (res != ERROR_SUCCESS || size <= 0) {
		return "";
	}
	std::vector<BYTE> value_data(size);
	res = ::RegQueryValueExA(hkey, key.c_str(), 0, &type, value_data.data(), &size);
	if (res != ERROR_SUCCESS) {
		return "";
	}

	return std::string(value_data.begin(), value_data.end());
}

